package com.gec.anan.driver.service.impl;

import com.alibaba.fastjson.JSON;
import com.gec.anan.common.execption.AnanException;
import com.gec.anan.common.result.ResultCodeEnum;
import com.gec.anan.driver.config.TencentCloudProperties;
import com.gec.anan.driver.service.CiService;
import com.gec.anan.driver.service.CosService;
import com.gec.anan.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    @Autowired
    private CiService ciService;

    public COSClient getPrivateCOSClient() {
        //1.初始化客户信息
        COSCredentials cred = new BasicCOSCredentials(tencentCloudProperties.getSecretId(),
                tencentCloudProperties.getSecretKey());
        //2.设置buket和cos跨域
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion(new Region(tencentCloudProperties.getRegion()));
        clientConfig.setHttpProtocol(HttpProtocol.https);
        //3.生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        //4.返回cos客户端对象
        return cosClient;
    }

    @Override
    public CosUploadVo upload(MultipartFile multipartFile, String path) {
        COSClient cosClient = this.getPrivateCOSClient();

        //1.调用cos进行文件上传
        //对象元数据信息
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentEncoding("UTF-8");
        metadata.setContentLength(multipartFile.getSize());
        metadata.setContentType(multipartFile.getContentType());

        //2.在bucket桶中保存文件
        //这里上传的是文件的全程，包含后缀（例如1.jpg）,要截取文件的后缀名称
        String fileType = multipartFile.getOriginalFilename().substring
                (multipartFile.getOriginalFilename().lastIndexOf("."));
        //上传路径，cos的文件夹
        String upLoadPath = "/driver/" + path + UUID.randomUUID().toString()
                .replaceAll("-", "") + fileType;
        //上传请求
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(), upLoadPath,
                    multipartFile.getInputStream(), metadata);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        //记录日志
        log.info("上传的文件请求："+ JSON.toJSONString(putObjectResult));

        //ci数据万象图片审核
        Boolean imageAuditing = ciService.imageAuditing(upLoadPath);
        if(!imageAuditing){
            cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(), upLoadPath);
            throw new AnanException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        }


        //3.返回CosUploadVo对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(upLoadPath);
        //图片临时访问url，回显使用
        String imageUrl = this.getImageUrl(upLoadPath);
        cosUploadVo.setShowUrl(imageUrl);
        return cosUploadVo;
    }


    //获取图像地址
    @Override
    public String getImageUrl(String path) {
        if(!StringUtils.hasText(path))return "";
        COSClient cosClient = this.getPrivateCOSClient();
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);

        //设置时间为15分钟
        Date date;
        date = new DateTime().plusMinutes(15).toDate();
        request.setExpiration(date);

        //调用方法
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }


}
